package com.gz.service;

import com.gz.dao.BillDao;
import com.gz.dao.MultiTableDao;
import com.gz.domain.Bill;
import com.gz.domain.MultiTableBean;
import jdk.nashorn.internal.ir.CallNode;

import java.util.List;
import java.util.UUID;

public class BillService {
    BillDao billDao=new BillDao();
    MenuService menuService=new MenuService();
    DiningTableService diningTableService=new DiningTableService();
    MultiTableDao multiTableDao=new MultiTableDao();

    //如果这里用事务，需要用ThreadLocal来解决，框架中比如mybatis提供了事务支持
    //编写点餐方法
    //1.生成账单
    //2.需要更新对应餐桌的状态

    public boolean orderMenu(int menuId,int nums,int diningTableId){
        //生成账单号，UUID
        String billId= UUID.randomUUID().toString();

        //将账单生成到bill表
        int update = billDao.update("insert into bill values(null,?,?,?,?,?,now(),'未结账')",
                billId, menuId, nums, menuService.getMenuById(menuId).getPrice() * nums, diningTableId);
        if(update<=0){
            return false;
        }
        //更新对应餐桌状态
        return diningTableService.updateDiningTableState(diningTableId,"就餐中");
    }

    public List<Bill> getBillList(){
        return billDao.queryMulti("select * from bill",Bill.class);
    }


    //返回全部账单并带有菜品名
    public List<MultiTableBean> getBillList2(){
        return multiTableDao.queryMulti("select bill.*,name from "+ //多表
                "bill,menu "+
                "where bill.menuId=menu.id", MultiTableBean.class);
    }


    //查看某个餐桌是否有未结账的账单
    public boolean hasPayBillByDiningTableId(int diningTableId){
            Bill bill=billDao.querySingle("select * from bill where diningTableId=? and state='未结账' limit 0,1",Bill.class,diningTableId);
        if(bill==null){
            return false;
        }
        return true;
    }

    //完成结账
    public boolean payBill(int diningTableId,String payMode){
        //1.修改bill表
        int update = billDao.update("update bill set state=? where diningTableId=? and state='未结账'", payMode, diningTableId);
        if(update<=0){
            return false;
        }
        //修改diningTable表
        if(!(diningTableService.updateDiningTableStateToFree(diningTableId,"空"))){
            return false;
        }
        return true;

    }
}
